package Controller

import (
	"encoding/json"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/gin-gonic/gin"
	"m/Global"
	"m/model"
	"m/response"
)

func ManagerLogin(context *gin.Context)  {
	// 获取参数
	fmt.Println("进入managerlogin")
	var requestManager = model.Manager{}
	json.NewDecoder(context.Request.Body).Decode(&requestManager)
	fmt.Println("获取到的数据：", "学号：", requestManager.Mno, "名字：", requestManager.Mname, "密码：", requestManager.Mpassword)
	Global.Sno = requestManager.Mno// 保存全局学号
	mno := requestManager.Mno
	//mname := requestManager.Mname
	spassword := requestManager.Mpassword
	// 数据验证
	fmt.Println("开始数据验证")
	if len(mno) < 1 {
		//response.Response(context, http.StatusUnprocessableEntity, 421, nil, "学号必须大于0位！")
		context.JSON(200, gin.H{
			"code":200,
			"msg":"学号不能为空",
		})
		return
	}
	if len(spassword) < 6 {
		//response.Response(context, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		context.JSON(200, gin.H{
			"code":200,
			"msg":"密码不能少于6位",
		})
		return
	}

	result := false
	if Global.Flag == true {
		// 应用redis，如果redis有管理员信息，就无需从数据库读取了
		fmt.Println("读取Redis，flag =", Global.Flag, "result =", result)
		r, err := redis.String(Global.CDb.Do("GET", "admin"))
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println("从Redis读取到的信息：", r)
		fmt.Println("执行Redis")
		if r == spassword {// 密码正确
			context.JSON(200, gin.H{
				"code":200,
				"msg":"使用Redis登陆成功",
			})
			return
		} else {// 密码错误
			//context.JSON(200, gin.H{
			//	"code":200,
			//	"msg":"Redis读取的密码错误",
			//})
			result = true
			//return
		}
	} // 没读到信息
	if Global.Flag == false || result == true {
		// 学号是否存在
		var manager model.Manager
		fmt.Println("不读取Redis，flag =", Global.Flag, "result =", result)
		Global.Db.Where("mno = ?", mno).First(&manager)
		fmt.Println("manager.Mno=", manager.Mno, "manager.Spassword=", manager.Mpassword)

		if manager.Mno == "" {
			//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":423, "msg":"用户不存在"})
			context.JSON(200, gin.H{
				"code": 200,
				"msg":  "用户不存在",
			})
			return
		}

		if manager.Mpassword != spassword {
			fmt.Println("数据库密码：", manager.Mpassword, "传入的密码：", spassword)
			//context.JSON(http.StatusBadRequest, gin.H{"code":400, "msg":"密码错误"})
			context.JSON(200, gin.H{
				"code": 200,
				"msg":  "密码错误",
			})
			return
		}
		// 发放token
		token, err := Global.ReaeaseTokec2(manager)
		if err != nil {
			context.JSON(200, gin.H{
				"code": 200,
				"msg":  "token发放失败!",
			})
			return
		}
		response.Success(context, gin.H{"token": token}, "登陆成功")

	}

}

